/* File: Menu.m - (Interactive) Unix shell version of Menu
 *
 * By: Christopher Lane (lane@sumex-aim.stanford.edu)
 *
 * Date: 10 November 1992
 *
 * Copyright: 1990, 1991 & 1992 by The Leland Stanford Junior University.
 * This program may be distributed without restriction for non-commercial use.
 */

#import <stdlib.h>
#import <getopt.h>

#import <appkit/Menu.h>
#import <appkit/Matrix.h>
#import <appkit/MenuCell.h>
#import <appkit/Application.h>

#define SELECTOR @selector(stop:)
#define KEYCODE '1'
#define TIMEOUT (30)

#define USAGE "usage: %s [-c char] [-t title] [-x xpos -y ypos] [-T seconds] item [item [...]]\n"
#define EXIT_USAGE (2)

@interface MenuApp : Application { }

- appDidInit:sender;

@end

@implementation MenuApp : Application

- appDidInit:sender
{
	[[self appIcon] orderOut:self];

	return self;
}

@end

void timer(DPSTimedEntry teNumber, double now, int status) { exit(status); }

void main(int argc, char *argv[])
{
	const char *title = NULL;
	double timeout = TIMEOUT;
	unsigned short keyCode = KEYCODE;
	int option, status = EXIT_SUCCESS;
	NXPoint point = { -1.0, -1.0 };
	DPSTimedEntry teNumber = NULL;
	
	while ((option = getopt(argc, argv, "c:t:x:y:T:")) != EOF)
		switch (option) {
		case 'c': keyCode = optarg[0]; break;
		case 't': title = optarg; break;
		case 'x': point.x = atof(optarg); break;
		case 'y': point.y = atof(optarg); break;
		case 'T': timeout = atol(optarg); break;
		default : status = EXIT_USAGE;
		}
	if(optind == argc) status = EXIT_USAGE;

	NXApp = [MenuApp new];

	if (status == EXIT_USAGE) (void) fprintf(stderr, USAGE, [NXApp appName]);
	else {
		int context = [NXApp activateSelf:YES];
		id menu = [Menu newTitle:(title == NULL) ? [NXApp appName] : title];

		if(point.x >= 0.0 && point.y >= 0.0) [menu moveTopLeftTo:point.x :point.y];

		for(option = optind; option < argc; option++)
			[[menu addItem:argv[option] action:SELECTOR keyEquivalent:keyCode++] setTarget:NXApp];

		[NXApp setMainMenu:[menu display]];

		if(timeout) teNumber = DPSAddTimedEntry(timeout, (DPSTimedEntryProc) &timer, (void *) EXIT_FAILURE, NX_BASETHRESHOLD);

		[NXApp run];

		if(timeout) DPSRemoveTimedEntry(teNumber);

		(void) printf("%s\n", [[[menu itemList] selectedCell] title]);

		if(context) (void) [NXApp activate:context];
		}

	[NXApp free];

	exit(status);
}
